﻿using System;
using System.Windows.Forms;
using McmWinFormsApplication1.Components;
using Polenter.Mcm;

namespace McmWinFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (DesignMode)
            {
                return;
            }

            // MCM initialization must be made after the UI synchronization context is created
            // the good place is the constructor of the main form its OnLoad event
            Env.Initialize();

            Env.Components.Add(this);
        }

        [MessageSubscriber(McmComponentContainer.MessagesChannelName,
            UIThreadSynchronizationMode.PostAsynchronousInUIThread)]
        private void handleCurrentOutputTextChangedMessage(CurrentOutputTextChangedMessage m)
        {
            outputTextBox.Text = Env.Components.First<CurrentOutputTextComponent>().CurrentOutputText;
        }

        private void executeButton_Click(object sender, EventArgs e)
        {
            Env.PostMessage(new ReverseTextRequestMessage(inputTextBox.Text));
        }

        [MessageSubscriber(McmComponentContainer.MessagesChannelName,
            UIThreadSynchronizationMode.PostAsynchronousInUIThread)]
        private void handleAsyncOperationRequestMessage(AsyncOperationRequestMessage m)
        {
            executeButton.Enabled = false;
            outputTextBox.Text = "Working...";
        }

        [MessageSubscriber(McmComponentContainer.MessagesChannelName,
            UIThreadSynchronizationMode.PostAsynchronousInUIThread)]
        private void handleAsyncOperationResponseMessage(AsyncOperationResponseMessage m)
        {
            executeButton.Enabled = true;
            outputTextBox.Text = string.Empty;
        }
    }
}